package com.example.demo.sys.menu.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.base.BaseController;
import com.example.demo.base.Result;
import com.example.demo.sys.menu.entity.SysMenu;
import com.example.demo.sys.menu.service.SysMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 权限菜单控制器
 *
 * @author haocj
 */
@RestController
@RequestMapping(value = "/sysMenu")
public class SysMenuController extends BaseController {

    @Autowired
    private SysMenuService menuService;


    @ModelAttribute
    public SysMenu get(@RequestParam(required=false) String id) {
        if (StringUtils.isNotBlank(id)){
            return menuService.get(id);
        }else{
            return new SysMenu();
        }
    }

    @RequestMapping(value = "/getById")
    public SysMenu getById(SysMenu sysMenu) {
        SysMenu menu = menuService.get(sysMenu);
        return menu;
    }

    /**
     * 菜单列表
     *
     * @param sysMenu
     * @return
     */
    @RequestMapping(value = "/info")
    public List<SysMenu> list(SysMenu sysMenu) {
//        sysMenu.setIsShows("0");
        return menuService.findList(sysMenu);
    }

    /**
     * 新增
     *
     * @param sysMenu
     * @return
     */
    @RequestMapping(value = "/save")
//    @RequiresPermissions("sys:menu:save")
    public Result save(SysMenu sysMenu) {
        menuService.save(sysMenu);
        return Result.success("保存成功");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
//    @RequiresPermissions("sys:menu:delete")
    public Result delete(@RequestParam("id") String[] ids) {
        menuService.delete(ids);
        return Result.success();
    }


    /**
     * 菜单数据
     *
     * @return
     */
    @RequestMapping(value = "/zTreeNodes")
    public Result<JSONArray> getZTreeNodes() {

        JSONArray array = new JSONArray();
        JSONObject object = null;
        List<SysMenu> list = menuService.findList(new SysMenu());
        for (SysMenu menu : list) {
            object = new JSONObject();
            object.put("id", menu.getId());
            object.put("pId", menu.getParentId());
            object.put("name", menu.getName());
            array.add(object);
        }
        return new Result<>(1, "success", array);
    }

}
